#coding:utf-8
import socket
import threading
from multiprocessing import Process, Queue
#import dataParse
import struct
#import pymysql
import datetime
import select
import os 
import json
import traceback
import sys
import time
import subprocess
sys.getdefaultencoding()
CWD_DIR = os.path.split(os.path.abspath(__file__) )[0]
address = "0.0.0.0"
port = 8800
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
epoll = select.epoll()
fd = sock.fileno()
sock.bind((address,port))
sock_dict = {}
sock_dict[fd] = sock
shumeipai ={}
epoll.register(fd,select.EPOLLIN)
sock.listen(20)
def server(q):
	while True:  
		try:
			events = epoll.poll(1)
			for fileno,event in events:#获取到的文件描述符和sock的相同就说明是一个新的连接
				if fileno == fd:
					(client,address) = sock.accept()

					#print ("来者地址",address)
					client.setblocking(0)#将新的连接进行注册，用来接收消息
					epoll.register(client.fileno(),select.EPOLLIN)
					sock_dict[client.fileno()] = client
				elif event & select.EPOLLIN:   #有可读事件激活
					#print ("fileno:",fileno)#返回套接字的文件描述符
					data = sock_dict[fileno].recv(128)
					
					if len(data) == 0:
						print ("client %d is not connected"%fileno )
						epoll.unregister(fileno)
					else:					
						if 'station_id' in data.decode():
							print ("收到基站来信",data.decode())
							datas =  data.decode()
							q.put(datas)
							#print("来者地址",sock_dict[fileno])
							datas=json.loads(datas)
							i=int(datas[0]['station_id'])
							print(i,type(i))
							shumeipai[i]=fileno
							#print("楼号ip",shumeipai[i])

						if 'action' in data.decode():
							print("收到控制信息",data)
							zhiling = data.decode()
							j = int((zhiling.split(';')[0]).split('=')[-1])
							print("控制%d号基站",j)
							try:
								sock_dict[shumeipai[int(j)]].send(data)
							except:
								print("没有这个基站")
		except:
			print("服务器正在重新启动")
			
def main():
	try:
		q = Queue()
		threads = []
		t1 = threading.Thread(target=server, args=(q,))
		threads.append(t1)
	#	t2 = threading.Thread(target=WriteDBProcess,args=(q,))
	#	threads.append(t2)
		for t in threads:
			t.start()
	except:
		print("服务器正在重新启动")
if __name__ == '__main__':
	main()
